package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.query.QueryObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @RequestMapping("list")
    public String list(@ModelAttribute("qo") QueryObject qo,Model model){
        return "/region/list";
    }
    @RequestMapping("selectByParentId")
    @ResponseBody
    public List selectByParentId(Long parentId,String type){
        List<Region> regions = regionService.selectByParentId(parentId);
        //判断是否获取treeview需要的数据
        if ("tree".equals(type)) {

            //用于封装treeview需要的结果
            ArrayList<Map> list = new ArrayList<>();
            //循环取出每一个region对象
            for (Region region : regions) {
                list.add(region.toTreeMap());
            }
            return list;
        }else{
            //返回原生数据
            return regions;
        }
    }
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region entity){
        JSONResult jsonResult = new JSONResult();
        try {
            regionService.saveOrUpdate(entity);
        } catch (Exception e) {
            jsonResult.mark(e.getMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }
    @RequestMapping("updateStatus")
    @ResponseBody
    public JSONResult updateStatus(Region entity){
        JSONResult jsonResult = new JSONResult();
        try {
            regionService.updateStatus(entity);;
        } catch (Exception e) {
            jsonResult.mark(e.getMessage());
            e.printStackTrace();
        }
        return jsonResult;

    }
}
